package insight.jsp.custom.taglib;

import insight.sm.constants.Constants;
import insight.sm.delegates.UserDelegate;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.io.IOUtils;

public class HeaderTagHandler extends TagSupport {

	private static final long serialVersionUID = 1L;

	public int doStartTag() throws JspException {
		try {
			// pageContext.getSession()
			JspWriter out = pageContext.getOut();
			String userName = ""
					+ pageContext.getSession().getAttribute(
							Constants.Session.CURRENT_USER_NAME);
			String userId = ""
					+ pageContext.getSession().getAttribute(
							Constants.Session.CURRENT_USER_ID);
			int msgCount = UserDelegate.getUnreadMessageCount(userId);
			String strOut = buildOutput("header.inc", userName, msgCount);
			out.println(strOut);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EVAL_BODY_INCLUDE;
	}

	public String buildOutput(String fileName, String userName, int msgCount) {
		InputStream in = this.getClass().getClassLoader()
				.getResourceAsStream(fileName);
		StringWriter writer = new StringWriter();
		try {
			IOUtils.copy(in, writer, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		String strOut = writer.toString();
		strOut = strOut
				.replace("${username}", userName)
				.replace(
						"${messages-bdg}",
						msgCount > 0 ? "<span class='badge badge-dark-red'>"
								+ msgCount + "</span>" : "")
				.replace(
						"${messages-lbl}",
						msgCount > 0 ? "<span class='label label-dark-red pull-right'>"
								+ msgCount + "</span>"
								: "");
		return strOut;
	}
}
